package com.rainflowerstone.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.widget.AppCompatImageView;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.rainflowerstone.R;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * @ Author     ：lwc
 * @ Date       ：Created in 17:40 2019/1/28
 * @ Description：${description}
 * @ Modified By：
 * @Version: $version$
 */
public class RainFlowerStoneTopSheet extends Dialog {

    private static final String TAG = "RainFlowerStoneTopSheet";
    // 动画时长
    private final static int mAnimationDuration = 200;
    // 持有 ContentView，为了做动画
    private View mContentView;


    public RainFlowerStoneTopSheet(@NonNull Context context) {
        super(context, R.style.QMUI_BottomSheet);
    }

    @Override
    public void show() {
        super.show();
        animateDown();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //noinspection ConstantConditions
        getWindow().getDecorView().setPadding(0, 150, 0, 0);

        // 在底部，宽度撑满
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.TOP | Gravity.CENTER;

        int screenWidth = QMUIDisplayHelper.getScreenWidth(getContext());
        int screenHeight = QMUIDisplayHelper.getScreenHeight(getContext());
        params.width = screenWidth < screenHeight ? screenWidth : screenHeight;
        getWindow().setAttributes(params);
        setCanceledOnTouchOutside(true);
    }

    @Override
    public void setContentView(int layoutResID) {
        mContentView = LayoutInflater.from(getContext()).inflate(layoutResID, null);
        super.setContentView(mContentView);
    }

    @Override
    public void setContentView(@NonNull View view, ViewGroup.LayoutParams params) {
        mContentView = view;
        super.setContentView(view, params);
    }

    public View getContentView() {
        return mContentView;
    }

    @Override
    public void setContentView(@NonNull View view) {
        mContentView = view;
        super.setContentView(view);
    }

    /**
     * BottomSheet动画
     */
    private void animateDown() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f
        );
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);
        mContentView.startAnimation(set);
    }

    public interface OnTopSheetShowListener {
        void onShow();
    }

    /**
     * 生成宫格类型的 {@link RainFlowerStoneTopSheet} 对话框。
     */
    public static class TopGridSheetBuilder implements View.OnClickListener {

        /**
         * item 出现在第一行
         */
        public static final int FIRST_LINE = 0;
        /**
         * item 出现在第二行
         */
        public static final int SECOND_LINE = 1;

        private OnSheetItemClickListener mOnSheetItemClickListener;
        private Context mContext;
        private RainFlowerStoneTopSheet mDialog;
        private SparseArray<View> mFirstLineViews;
        private SparseArray<View> mSecondLineViews;
        private ViewGroup mTopButtonContainer;
        private ImageView mTopButton;
        //        private TextView  mTvButton;
        private int mMiniItemWidth = -1;
        private boolean mIsShowButton = true;
        private Typeface mTopButtonTypeFace = null;
        private CharSequence mButtonText = null;
        private View.OnClickListener mButtonClickListener = null;
        private Typeface mItemTextTypeFace = null;

        public TopGridSheetBuilder(Context context) {
            mContext = context;
            mFirstLineViews = new SparseArray<>();
            mSecondLineViews = new SparseArray<>();
        }

        public TopGridSheetBuilder addItem(int imageRes, CharSequence textAndTag, @Style int style) {
            return addItem(imageRes, textAndTag, textAndTag, style, 0);
        }

        public TopGridSheetBuilder addItem(int imageRes, CharSequence text, Object tag, @Style int style) {
            return addItem(imageRes, text, tag, style, 0);
        }

        public TopGridSheetBuilder addItem(int imageRes, CharSequence text, Object tag, @Style int style, int subscriptRes) {
            RainFlowerStoneSheetItemView itemView = createItemView(AppCompatResources.getDrawable(mContext, imageRes), text, tag, subscriptRes);
            return addItem(itemView, style);
        }

        public TopGridSheetBuilder addItem(View view, @Style int style) {
            switch (style) {
                case FIRST_LINE:
                    mFirstLineViews.append(mFirstLineViews.size(), view);
                    break;
                case SECOND_LINE:
                    mSecondLineViews.append(mSecondLineViews.size(), view);
                    break;
            }
            return this;
        }


        public RainFlowerStoneSheetItemView createItemView(Drawable drawable, CharSequence text, Object tag, int subscriptRes) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            RainFlowerStoneSheetItemView itemView = (RainFlowerStoneSheetItemView) inflater.inflate(getItemViewLayoutId(), null, false);
            TextView titleTV = (TextView) itemView.findViewById(R.id.grid_item_title);
            if (mItemTextTypeFace != null) {
                titleTV.setTypeface(mItemTextTypeFace);
            }
            titleTV.setText(text);

            itemView.setTag(tag);
            itemView.setOnClickListener(this);
            AppCompatImageView imageView = (AppCompatImageView) itemView.findViewById(R.id.grid_item_image);
            imageView.setImageDrawable(drawable);

            if (subscriptRes != 0) {
                ViewStub stub = (ViewStub) itemView.findViewById(R.id.grid_item_subscript);
                View inflated = stub.inflate();
                ((ImageView) inflated).setImageResource(subscriptRes);
            }
            return itemView;
        }

        public TopGridSheetBuilder setOnSheetItemClickListener(OnSheetItemClickListener onSheetItemClickListener) {
            mOnSheetItemClickListener = onSheetItemClickListener;
            return this;
        }

        @Override
        public void onClick(View v) {
            if (mOnSheetItemClickListener != null) {
                mOnSheetItemClickListener.onClick(mDialog, v);
            }
        }

        public interface OnSheetItemClickListener {
            void onClick(RainFlowerStoneTopSheet dialog, View itemView);
        }

        public RainFlowerStoneTopSheet build() {
            mDialog = new RainFlowerStoneTopSheet(mContext);
            View contentView = buildViews();
            mDialog.setContentView(contentView,
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return mDialog;
        }

        private View buildViews() {

            LinearLayout baseLinearLayout;
            baseLinearLayout = (LinearLayout) View.inflate(mContext, getContentViewLayoutId(), null);
            //第一行
            LinearLayout firstLine = (LinearLayout) baseLinearLayout.findViewById(R.id.top_sheet_first_linear_layout);
            //第二行
            LinearLayout secondLine = (LinearLayout) baseLinearLayout.findViewById(R.id.top_sheet_second_linear_layout);
            mTopButtonContainer = (ViewGroup) baseLinearLayout.findViewById(R.id.top_sheet_button_container);
            mTopButton = (ImageView) baseLinearLayout.findViewById(R.id.top_sheet_close_button);
//            mTvButton=(TextView)baseLinearLayout.findViewById(R.id.tv_sheet_other_button);
            int maxItemCountEachLine = Math.max(mFirstLineViews.size(), mSecondLineViews.size());
            int screenWidth = QMUIDisplayHelper.getScreenWidth(mContext);
            int screenHeight = QMUIDisplayHelper.getScreenHeight(mContext);
            int width = screenWidth < screenHeight ? screenWidth : screenHeight;
            int itemWidth = calculateItemWidth(width, maxItemCountEachLine, firstLine.getPaddingLeft(), firstLine.getPaddingRight());
            addViewsInSection(mFirstLineViews, firstLine, itemWidth);
            addViewsInSection(mSecondLineViews, secondLine, itemWidth);
            boolean hasFirstLine = mFirstLineViews.size() > 0;
            boolean hasSecondLine = mSecondLineViews.size() > 0;
            if (!hasFirstLine) {
                firstLine.setVisibility(View.GONE);
            }
            if (!hasSecondLine) {
                if (hasFirstLine) {
                    firstLine.setPadding(
                            firstLine.getPaddingLeft(),
                            firstLine.getPaddingTop(),
                            firstLine.getPaddingRight(),
                            0);
                }
                secondLine.setVisibility(View.GONE);
            }

            // button 在用户自定义了contentView的情况下可能不存在
            if (mTopButtonContainer != null) {
                if (mIsShowButton) {
                    mTopButtonContainer.setVisibility(View.VISIBLE);
                    baseLinearLayout.setPadding(baseLinearLayout.getPaddingLeft(),
                            baseLinearLayout.getPaddingTop(),
                            baseLinearLayout.getPaddingRight(),
                            0);
                } else {
                    mTopButtonContainer.setVisibility(View.GONE);
                }
//                if (mTopButtonTypeFace != null) {
//                    mTvButton.setTypeface(mTopButtonTypeFace);
//                }
//                if (mButtonText != null) {
//                    mTvButton.setText(mButtonText);
//                }

                if (mButtonClickListener != null) {
                    mTopButton.setOnClickListener(mButtonClickListener);
                } else {
                    mTopButton.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                        }
                    });


                }
            }
            return baseLinearLayout;
        }

        protected int getItemViewLayoutId() {
            return R.layout.rainflowerstone_top_sheet_grid_item;
        }

        protected int getContentViewLayoutId() {
            return R.layout.rainflowerstone_top_sheet_grid;
        }

        /**
         * 拿个数最多的一行，去决策item的平铺/拉伸策略
         */
        private int calculateItemWidth(int width, int maxItemCountInEachLine, int paddingLeft, int paddingRight) {
            if (mMiniItemWidth == -1) {
                mMiniItemWidth = QMUIResHelper.getAttrDimen(mContext, R.attr.qmui_bottom_sheet_grid_item_mini_width);
            }
            final int parentSpacing = width - paddingLeft - paddingRight;
            int itemWidth = mMiniItemWidth;
            // 看是否需要把 Item 拉伸平分 parentSpacing
            if (maxItemCountInEachLine >= 3
                    && parentSpacing - maxItemCountInEachLine * itemWidth > 0
                    && parentSpacing - maxItemCountInEachLine * itemWidth < itemWidth) {
                int count = parentSpacing / itemWidth;
                itemWidth = parentSpacing / count;
            }
            // 看是否需要露出半个在屏幕边缘
            if (itemWidth * maxItemCountInEachLine > parentSpacing) {
                int count = (width - paddingLeft) / itemWidth;
                itemWidth = (int) ((width - paddingLeft) / (count + .5f));
            }
            return itemWidth;
        }

        private void addViewsInSection(SparseArray<View> items, LinearLayout parent, int itemWidth) {
            for (int i = 0; i < items.size(); i++) {
                View itemView = items.get(i);
                setItemWidth(itemView, itemWidth);
                parent.addView(itemView);
            }
        }

        private void setItemWidth(View itemView, int itemWidth) {
            LinearLayout.LayoutParams itemLp;
            if (itemView.getLayoutParams() != null) {
                itemLp = (LinearLayout.LayoutParams) itemView.getLayoutParams();
                itemLp.width = itemWidth;
            } else {
                itemLp = new LinearLayout.LayoutParams(itemWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
                itemView.setLayoutParams(itemLp);
            }
            itemLp.gravity = Gravity.TOP;
        }

        @Retention(RetentionPolicy.SOURCE)
        @IntDef({FIRST_LINE, SECOND_LINE})
        public @interface Style {
        }
    }

}


